package com.dodo.blog.ui.page.admin;

import com.dodo.blog.model.Playground;
import com.dodo.blog.model.Role;
import com.dodo.blog.server.PlaygroundService;
import com.dodo.blog.ui.ajax.Response;
import com.dodo.blog.ui.ajax.annotation.GetModel;
import com.dodo.blog.ui.ajax.annotation.SetModel;
import com.dodo.blog.ui.authorization.Authorized;
import com.dodo.blog.ui.component.composite.FieldSet;
import com.dodo.blog.ui.component.composite.FormRow;
import com.dodo.blog.ui.component.container.Form;
import com.dodo.blog.ui.component.input.AjaxSubmitButton;
import com.dodo.blog.ui.component.input.Anchor;
import com.dodo.blog.ui.component.input.TextArea;
import com.dodo.blog.ui.component.input.TextBox;
import com.dodo.blog.ui.page.AbstractPage;

import javax.inject.Inject;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
@Authorized( roles = {Role.ADMIN} )
public class PlaygroundEdit
        extends AbstractPage
{
    private static final long serialVersionUID = 1L;

    public static final String PLAYGROUND_ID = "id";

    private static PlaygroundService playgroundService;

    private static final String PLAYGROUND_FORM = "playground-form";

    @SetModel( name = PLAYGROUND_FORM )
    public Response setModel( Playground playground )
    {
        playgroundService.savePlayground( playground );

        return Response.redirect( PlaygroundList.class );
    }

    @GetModel( name = PLAYGROUND_FORM )
    public Playground getModel()
    {
        Long id = getLongParameter( PLAYGROUND_ID );

        Playground playground;
        if ( id != null )
        {
            playground = playgroundService.getPlaygroundById( id );
        }
        else
        {
            playground = new Playground();
        }

        return playground;
    }

    @Override
    public void onRender()
    {
        setHeader( localize( "header.playgroundEdit" ) );

        Form form = new Form( PLAYGROUND_FORM, Playground.class );
        add( form );

        FieldSet fieldSet = new FieldSet( localize( "title.playgroundEdit" ) );
        form.add( fieldSet );

        fieldSet.add( new FormRow( localize( "label.description" ), new TextBox( "description" ).setAutoFocus( true ) ) );
        fieldSet.add( new FormRow( localize( "label.code" ), new TextArea( "code" ) ) );

        form.add( new AjaxSubmitButton( "save", localize( "button.save" ) ) );
        form.add( new Anchor( "cancel", localize( "button.cancel" ), PlaygroundList.class ) );
    }

    @Inject
    public void setPlaygroundService( PlaygroundService playgroundService )
    {
        PlaygroundEdit.playgroundService = playgroundService;
    }
}